<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>排行榜 - 俄罗斯方块</title>
    <!-- TailwindCSS via CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome via Cloudflare CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
             /* Consistent background with start screen */
             background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        /* Style for loading spinner */
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1); /* Lighter border for dark text */
            border-radius: 50%;
            border-top-color: #4f46e5; /* Indigo */
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        /* Hide elements by default */
        .hidden {
            display: none;
        }
        /* Style for table */
        th, td {
            padding: 0.75rem 1rem; /* Adjust padding */
            text-align: left;
        }
        /* Add subtle hover effect to rows */
        tbody tr:hover {
            background-color: #f0f0f8; /* Light purple/gray hover */
        }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center p-4 bg-gray-100">
    <!-- Main Content Card -->
    <div class="bg-white rounded-xl shadow-2xl p-6 md:p-10 max-w-2xl w-full transform transition-all duration-300">

        <!-- Leaderboard Title -->
        <h1 class="text-3xl md:text-4xl font-extrabold text-center text-transparent bg-clip-text bg-gradient-to-r from-yellow-500 to-orange-500 mb-6">
            <i class="fas fa-trophy mr-2 text-yellow-500"></i> 排行榜
        </h1>

        <!-- Loading State Indicator -->
        <div id="loadingIndicator" class="text-center py-10 hidden">
            <div class="spinner mx-auto mb-4"></div>
            <p class="text-gray-500">正在加载排行榜...</p>
        </div>

        <!-- Error State Indicator -->
        <div id="errorIndicator" class="text-center py-10 hidden">
            <i class="fas fa-exclamation-triangle text-red-500 text-4xl mb-4"></i>
            <p class="text-red-600">加载排行榜失败。</p>
            <p class="text-gray-500 text-sm mt-1">请稍后重试或检查网络连接。</p>
        </div>

        <!-- Leaderboard Table Container -->
        <div id="leaderboardContent" class="overflow-x-auto hidden"> <!-- Hide initially, show after load -->
             <table class="min-w-full divide-y divide-gray-200 border border-gray-200 rounded-lg shadow-sm">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="w-16 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                            排名
                        </th>
                        <th scope="col" class="text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            玩家昵称
                        </th>
                        <th scope="col" class="w-32 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            分数
                        </th>
                    </tr>
                </thead>
                <tbody id="leaderboardBody" class="bg-white divide-y divide-gray-200">
                    <!-- Leaderboard entries will be populated here by JS -->
                    <!-- Example Row Structure (for reference): -->
                    <!--
                    <tr>
                        <td class="text-center font-medium text-gray-900">1</td>
                        <td class="text-gray-700">Player One</td>
                        <td class="text-right font-semibold text-blue-600">50000</td>
                    </tr>
                    <tr class="bg-gray-50"> // Alternating row color
                        <td class="text-center font-medium text-gray-900">2</td>
                        <td class="text-gray-700">Another Player</td>
                        <td class="text-right font-semibold text-blue-600">45000</td>
                    </tr>
                    -->
                </tbody>
            </table>
             <p id="noScoresMessage" class="text-center text-gray-500 py-6 hidden">
                <i class="fas fa-ghost mr-2"></i> 还没有分数记录，快去创造一个吧！
            </p>
        </div>


        <!-- Action Buttons -->
        <div class="mt-8 flex flex-col sm:flex-row gap-3 justify-center">
            <button id="refreshBtn" class="w-full sm:w-auto bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-5 rounded-lg shadow-sm transition duration-200 flex items-center justify-center">
                <i class="fas fa-sync-alt mr-2"></i> 刷新列表
            </button>
            <button id="mainMenuBtn" class="w-full sm:w-auto bg-gray-500 hover:bg-gray-600 text-white font-semibold py-2 px-5 rounded-lg shadow-sm transition duration-200 flex items-center justify-center">
                <i class="fas fa-home mr-2"></i> 返回主菜单
            </button>
        </div>

    </div>

    <!-- JavaScript for fetching and rendering data -->
    <script>
        const loadingIndicator = document.getElementById('loadingIndicator');
        const errorIndicator = document.getElementById('errorIndicator');
        const leaderboardContent = document.getElementById('leaderboardContent');
        const leaderboardBody = document.getElementById('leaderboardBody');
        const noScoresMessage = document.getElementById('noScoresMessage');
        const refreshBtn = document.getElementById('refreshBtn');
        const mainMenuBtn = document.getElementById('mainMenuBtn');

        // --- Mock Data Generation ---
        const generateMockLeaderboard = (count = 10) => {
            const names = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Heidi", "Ivan", "Judy", "Kevin", "Linda"];
            const scores = [];
            for (let i = 0; i < count; i++) {
                scores.push({
                    // Use Mock.js style random generation if available, otherwise simple random
                    playerName: names[Math.floor(Math.random() * names.length)] + Math.floor(Math.random() * 100),
                    score: Math.floor(Math.random() * (50000 - 1000 + 1)) + 1000,
                    // timestamp: new Date(Date.now() - Math.random() * 1000 * 3600 * 24 * 7).toISOString() // Optional timestamp
                });
            }
            // Sort by score descending
            return scores.sort((a, b) => b.score - a.score);
        };
        // --- End Mock Data ---


        // --- Function to Render Leaderboard ---
        const renderLeaderboard = (data) => {
            leaderboardBody.innerHTML = ''; // Clear previous entries
            noScoresMessage.classList.add('hidden'); // Hide no scores message initially

            if (!data || data.length === 0) {
                 noScoresMessage.classList.remove('hidden'); // Show if no data
                 return;
            }

            data.forEach((entry, index) => {
                const rank = index + 1;
                const row = document.createElement('tr');
                // Add alternating background color
                if (index % 2 !== 0) {
                    row.classList.add('bg-gray-50');
                }

                // Rank Cell
                const rankCell = document.createElement('td');
                rankCell.classList.add('text-center', 'font-medium');
                if (rank === 1) rankCell.innerHTML = '<i class="fas fa-crown text-yellow-500"></i>';
                else if (rank === 2) rankCell.innerHTML = '<i class="fas fa-medal text-gray-400"></i>';
                else if (rank === 3) rankCell.innerHTML = '<i class="fas fa-medal text-orange-400"></i>';
                else rankCell.textContent = rank;
                rankCell.classList.add(rank <= 3 ? 'text-lg' : 'text-gray-900'); // Style top 3 ranks

                // Name Cell
                const nameCell = document.createElement('td');
                nameCell.classList.add('text-gray-700', 'truncate'); // Truncate long names if needed
                nameCell.textContent = entry.playerName;

                // Score Cell
                const scoreCell = document.createElement('td');
                scoreCell.classList.add('text-right', 'font-semibold', 'text-blue-600');
                scoreCell.textContent = entry.score.toLocaleString(); // Format score

                row.appendChild(rankCell);
                row.appendChild(nameCell);
                row.appendChild(scoreCell);
                leaderboardBody.appendChild(row);
            });
        };

        // --- Function to Fetch Leaderboard Data (Simulated) ---
        const fetchLeaderboardData = async () => {
            loadingIndicator.classList.remove('hidden');
            errorIndicator.classList.add('hidden');
            leaderboardContent.classList.add('hidden'); // Hide content while loading
            noScoresMessage.classList.add('hidden');
            leaderboardBody.innerHTML = ''; // Clear table body

            console.log('Fetching leaderboard data...');

            try {
                // Simulate network delay
                await new Promise(resolve => setTimeout(resolve, 1000));

                // Simulate API call success/failure
                const success = Math.random() > 0.15; // 85% success rate

                if (success) {
                    // Replace with actual fetch call:
                    // const response = await fetch('/api/scores?limit=10'); // Fetch top 10
                    // if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                    // const data = await response.json();
                    // const leaderboardData = data.data; // Assuming API returns { status, message, data }

                    // Using mock data for simulation:
                    const leaderboardData = generateMockLeaderboard(10); // Get top 10 mock scores
                    console.log('Data fetched:', leaderboardData);
                    renderLeaderboard(leaderboardData);
                    leaderboardContent.classList.remove('hidden'); // Show content
                } else {
                    throw new Error('Simulated API fetch error');
                }

            } catch (error) {
                console.error('Failed to fetch leaderboard:', error);
                errorIndicator.classList.remove('hidden'); // Show error message
            } finally {
                loadingIndicator.classList.add('hidden'); // Hide loading indicator
            }
        };

        // --- Event Listeners ---
        refreshBtn.addEventListener('click', fetchLeaderboardData);

        mainMenuBtn.addEventListener('click', () => {
            console.log('返回主菜单按钮被点击');
            // TODO: Navigate back to the Start Game screen
            window.location.href = '/'; // Navigate to root/start screen
        });

        // --- Initial Load ---
        document.addEventListener('DOMContentLoaded', fetchLeaderboardData);

    </script>
</body>
</html>
